# -*- coding: utf-8 -*-
# time: 2023/8/3 8:27
# file: childWin.py
# author: hanson
import tkinter as tk
import dataApi


class ChildWin(object):
    def __init__(self, master=None,info_text=None, clientId=None, pwd=None):
        self.root = master
        self.winName = "自动化配置"
        self.clientId = clientId
        self.pwd = pwd
        self.info_text = info_text

    def auto_win(self):
        # 创建弹出窗口
        global popup
        popup = tk.Toplevel(self.root)
        # get main window position
        root_x = self.root.winfo_rootx()
        root_y = self.root.winfo_rooty()
        win_x = root_x + 350
        win_y = 0 + 250
        popup.title(self.winName)
        popup.geometry(f'250x250+{win_x}+{win_y}')  # 设置新窗口的大小和位置

        # 向弹出窗口中添加标签和按钮
        # label = Label(popup, text="这是mqClient配置！")
        # label.pack()
        lab0 = tk.Label(popup, text='triggerId')
        lab1 = tk.Label(popup, text='序列ID')  # 创建账号标签
        lab2 = tk.Label(popup, text='状态(2|3)')  # 创建密码标签
        self.tri_en = tk.Entry(popup)  # 创建文本框
        self.seq_en = tk.Entry(popup)  # 创建文本框
        self.stat_en = tk.Entry(popup, textvariable=tk.IntVar(value=2))  # 创建文本框
        btn = tk.Button(popup, text='获取数据', bg='#C6D3CD', width=10, height=1,
                        command=self.autoApi)  # 把按钮和函数dayin绑定，点击按钮时，执行此函数

        lab0.grid(row=0, column=0)
        self.tri_en.grid(row=0, column=1)
        lab1.grid(row=1, column=0)
        self.seq_en.grid(row=1, column=1)
        lab2.grid(row=2, column=0)
        self.stat_en.grid(row=2, column=1)
        btn.grid(row=3, column=0, columnspan=1)

        #button = tk.Button(popup, text="关闭", command=popup.destroy)
        btn_back = tk.Button(popup, text='回调请求', bg='#A89DAE',  width=10, height=1,
                             command=self.autoBackApi)
        # button.pack()
        btn_back.grid(row=3, column=1, columnspan=1)
        popup.attributes("-toolwindow", 1)  # 无最大化，最小化
        popup.attributes('-topmost', 1)  # 窗口置顶其它窗体之上
        popup.transient(self.root)  # 窗口只置顶root之上
        popup.resizable(False, False)  # 不可调节窗体大小

    def autoApi(self):
        tri = self.tri_en.get()
        if tri != '':
            result = dataApi.getTriJson("trigger", tri, self.clientId, self.pwd)
        else:
            result = dataApi.getTriJson("sequence", self.seq_en.get(), self.clientId, self.pwd)

        print(result)
        a, res = dataApi.checkResult(result)
        print(res)
        if a == 1:
            self.info_text.insert(tk.END, res + " \n")
            popup.destroy()  # 注销窗口

    def autoBackApi(self):
        tri = self.tri_en.get()
        if tri != '':
            result = dataApi.backTriJson("trigger", tri, self.clientId, self.pwd, 2)
        else:
            result = dataApi.backTriJson("sequence", self.seq_en.get(), self.clientId, self.pwd, 2)
        a, res = dataApi.checkResult(result)
        if a == 1:
            self.info_text.insert(tk.END, res + " \n")
